using efcore.core.Models;
using Microsoft.EntityFrameworkCore;
using System.Transactions;
using MySqlConnector;
using 保存数据.Models;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Reflection.Metadata;
using Newtonsoft.Json;

namespace Test_保存
{
    public class Tests
    {
        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void 开放式并发1()
        {
            using (var context = new BloggingContext())
            {
                Convert.ToBase64String()
            }
        }

        [Test]
        public void 开放式并发()
        {
            using (var context = new BloggingContext())
            {
                var person = context.Persons.Single(b => b.FirstName == "John");
                person.FirstName = "Paul";
                context.SaveChanges();
            }
        }


        [Test]
        public void Test1()
        {
            using (var context = new BloggingContext())
            {
                var blog = context.Blogs.Include(blog1 => blog1.Posts)
                    .First(b => b.Url == "http://blogs.msdn.com/dotnet");
                context.RemoveRange(blog.Posts);
                context.Remove(blog);
                context.SaveChanges();
            }
        }


        [Test]
        public void 单个SaveChanges中的多个操作()
        {
            using (var context = new BloggingContext())
            {
                context.Database.AutoTransactionsEnabled = false;
                // add
                context.Blogs.Add(new Blog { Url = "http://example.com/blog_one" });
                context.Blogs.Add(new Blog
                {
                    BlogId = 17,
                    Url = "http://example.com/blog_two"
                });


                context.SaveChanges();
            }
        }

        [Test]
        public void 添加新实体的关系图()
        {
            using (var context = new BloggingContext())
            {
                var blog = new Blog
                {
                    Url = "http://blogs.msdn.com/dotnet",
                    Posts = new List<Post>
                    {
                        new Post { Title = "Intro to C#" },
                        new Post { Title = "Intro to VB.NET" },
                        new Post { Title = "Intro to F#" }
                    }
                };

                context.Blogs.Add(blog);
                context.SaveChanges();
            }
        }

        [Test]
        public void 事务()
        {
        }

        public void Gengxin()
        {
            using var context = new BloggingContext();
            var blogs = context.Blogs
                .Where(blog => blog.Url == "我是一个人1")
                .ToList();

            Console.WriteLine($"我说的分厘卡圣诞节反射疗法{blogs}");

            foreach (var blog in blogs)
            {
                blog.Url = "我是一个人";
            }

            context.SaveChanges();

            context.Blogs.Add(new Blog
            {
                BlogId = 17,
                Url = "http://example.com/blog_two"
            });
            context.SaveChanges();
        }


        [Test]
        public void Test111()
        {
            using var scope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted });
            using var context = new BloggingContext();
            try
            {
                context.Blogs.Add(new Blog { Url = "https://devblogs.microsoft.com/visualstudio/" });
                context.Blogs.Add(new Blog { Url = "https://devblogs.microsoft.com/aspnet/" });

                context.SaveChanges();

                Gengxin();
                // when disposed if either commands fails
                scope.Complete();
            }
            catch (Exception)
            {
                // TODO: Handle failure
            }
        }


        [Test]
        public void 附加()
        {
            var context = new BloggingContext();
            var blog = new Blog { BlogId = 250 };

            var blogs = context.Blogs.Find(250);

            //
            // context.ChangeTracker.DetectChanges();


            var serialized = JsonConvert.SerializeObject(
                blogs,
                new JsonSerializerSettings
                    { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented });

            Console.WriteLine(serialized);

            // 现在可以安全地读取或更新该实体
            // context.Entry(blog).State = EntityState.Modified; // 如果需要修改
            context.SaveChanges();



        }

        [Test]
        public void 附加1()
        {
            UpdatePostsFromJsonWithIdentityResolution("""
                                                      {
                                                        "BlogId": 250,
                                                        "Url": "fengliulinc.com1",
                                                        "Posts": null
                                                      }

                                                      """);
        }


        public static void UpdatePostsFromJsonWithIdentityResolution(string json)
        {
            using var context = new BloggingContext();

            var blog = JsonConvert.DeserializeObject<Blog>(json);

            context.ChangeTracker.TrackGraph(
                blog, node =>
                {
                    var keyValue = node.Entry.Property("BlogId").CurrentValue;
                    var entityType = node.Entry.Metadata;

                    var existingEntity = node.Entry.Context.ChangeTracker.Entries()
                        .FirstOrDefault(
                            e => Equals(e.Metadata, entityType)
                                 && Equals(e.Property("BlogId").CurrentValue, keyValue));

                    if (existingEntity == null)
                    {
                        Console.WriteLine($"Tracking {entityType.DisplayName()} entity with key value {keyValue}");

                        node.Entry.State = EntityState.Modified;
                    }
                    else
                    {
                        Console.WriteLine(
                            $"Discarding duplicate {entityType.DisplayName()} entity with key value {keyValue}");
                    }
                });


            context.SaveChanges();
        }

        [Test]
        public void 查询()
        {
            using (var context = new BloggingContext())
            {

                var blogs = context.Blogs
                    .Single(b => b.BlogId == 250);

                var nextPage = context.Posts
                    .OrderBy(b => b.PostId);
                    
                    
                    nextPage.Skip(1)
                    .Take(10)
                    .ToList();

                var serialized = JsonConvert.SerializeObject(
              blogs,
              new JsonSerializerSettings
              { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented });

                Console.WriteLine(serialized);

            }
        }
    }
}